package _interview75;

/**
 * 443. 压缩字符串
 */
public class No443 {
    public int compress(char[] chars) {
        int write = 0;
        char cur = chars[0];
        int curNum = 0;
        for (char c : chars) {
            if (c == cur) {
                curNum++;
            } else {
                write = write(chars, write, cur, curNum);
                cur = c;
                curNum = 1;
            }
        }

        write = write(chars, write, cur, curNum);
        return write;
    }

    private int write(char[] chars, int write, char cur, int curNum) {
        chars[write++] = cur;
        if (curNum > 1) {
            int multi = 0;
            int tempCurNum = curNum;
            while (tempCurNum > 0) {
                tempCurNum /= 10;
                multi++;
            }
            for (int j = 0; j < multi; j++) {
                int temp = (int) (curNum / Math.pow(10, multi - j - 1));
                chars[write++] = (char) ((temp % 10) + '0');
            }
        }
        return write;
    }
}
